package com.sunyard.wx.demo.controller;

import com.alibaba.fastjson.JSON;
import com.sunyard.wx.demo.entity.User;
import com.sunyard.wx.demo.repository.UserRepository;
import com.sunyard.wx.demo.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Created by xi.w on 2018-04-17.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/list")
    public String getUser(Model model) {
        List<User> all = userRepository.findAll();
        logger.info("查询用户信息，user=【{}】", JSON.toJSONString(all));
        model.addAttribute("users", all);
        return "hello";
    }

    @PostMapping("/add")
    public String getUsers(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        userRepository.save(user);
        logger.info("保存用户信息，user=【{}】", JSON.toJSONString(userVo));
        return "redirect:/user/list";
    }

    @GetMapping("/to/add")
    public String toAdd(UserVo userVo) {
        return "add";
    }
}
